<template>
    <div class="daily-detail-container">
        <el-skeleton :loading="skeletonLoading" animated>
            <template #template>
                <div style="padding: 20px;">
                    <el-skeleton-item variant="h1" style="width: 30%" />
                    <el-skeleton-item variant="text" style="width: 20%; margin-top: 16px;" />
                    <el-skeleton-item variant="text" style="width: 100%; margin-top: 16px;" />
                    <el-skeleton-item variant="text" style="width: 100%; margin-top: 16px;" />
                    <el-skeleton-item variant="text" style="width: 100%; margin-top: 16px;" />
                </div>
            </template>
        </el-skeleton>
        <!-- 中央转圈加载：仅在点击“下一个”导航时显示，不影响布局 -->
        <div v-if="navigatingNext" class="next-loading-overlay" aria-live="polite" aria-busy="true">
            <div class="next-loading-content">
                <div class="ring-spinner" role="status" aria-label="加载中"></div>
                <div class="next-loading-text">正在加载下一篇日报...</div>
                <div class="next-loading-subtext">请稍候</div>
            </div>
        </div>
        <!-- 日报头部信息：已按需求移除标题显示 -->

        <!-- 已读人员列表 -->
        <div class="readers-container">
            <div class="readers-header">
                <div class="readers-left">
                    <el-icon class="content-icon">
                        <User />
                    </el-icon>
                    <span class="readers-label">{{ reportTitle }}</span>
                </div>
                <el-tag size="small" class="readers-count">已读 {{ readers.length }} 人</el-tag>
            </div>
            <div class="readers-list">
                <el-tag v-for="reader in readers" :key="reader.userUUID" class="reader-tag">
                    {{ reader.userName }}
                </el-tag>
            </div>
        </div>

        <!-- 工作内容区域 -->
        <div class="work-content-container">
            <!-- 筛选与导航：移到标题上方 -->
            <div class="work-content-filters">
                <div class="filters-group" :class="{ 'is-loading-next': navigatingNext }">
                    <el-badge :value="selectIds.length || 0" :max="999" class="isread-count-badge" type="primary">
                        <el-select v-model="filterIsRead" size="small" class="filter-select" placeholder="是否已读">
                            <el-option :value="1" label="已读" />
                            <el-option :value="2" label="未读" />
                            <el-option :value="3" label="全部" />
                        </el-select>
                    </el-badge>
                    <el-select
                        v-model="filterNickName"
                        size="small"
                        class="filter-input"
                        placeholder="用户名"
                        clearable
                        filterable
                        :teleported="false"
                        :popper-class="'user-select-popper'"
                        @change="onUserChange"
                        @clear="onUserClear"
                    >
                        <el-option
                            v-for="u in userOptions"
                            :key="u.value"
                            :label="u.label"
                            :value="u.value"
                        />
                    </el-select>
                    <el-divider direction="vertical" class="filters-divider" />
                    
                    <el-button type="success" size="small" class="next-button" @click="goNext" :loading="navigatingNext" :disabled="nextDisabled || navigatingNext">
                        {{ navigatingNext ? '正在加载下一篇' : '下一个' }}
                        <el-icon v-if="!navigatingNext" style="margin-left:4px;"><ArrowRight /></el-icon>
                    </el-button>
                </div>
            </div>

            <div class="work-content-header">
                <div class="work-content-header-left">
                    <el-icon class="content-icon">
                        <List />
                    </el-icon>
                    <h2 class="content-title">工作内容</h2>
                </div>
                <div class="work-content-header-right">
                    <!-- 移动端评论按钮 -->
                    <el-button 
                        v-if="isMobile()"
                        type="primary" 
                        size="small" 
                        @click="toggleComments"
                        class="mobile-comment-btn"
                    >
                        <el-icon>
                            <ChatLineRound />
                        </el-icon>
                        评论 {{ comments.length }}
                    </el-button>
                </div>
            </div>

            <!-- 工作内容展示 -->
            <div class="work-items-container" v-if="currentReport.workItems" ref="workContentRef">
                <!-- 别人安排的工作 -->
                <div class="work-item-section" v-if="getWorkItemsByType(1).length > 0">
                    <div class="section-header">
                        <h3 class="section-title">别人安排的工作</h3>
                    </div>
                    <div v-for="(item, index) in getWorkItemsByType(1)" :key="`assigned-${index}`" class="work-item">
                        <div class="plain-text-item">
                            <span class="plain-text-content">
                                【{{ item.itemName }}】【{{ item.assigner.replace(/\n/g, '') }}】安排【{{
                                    item.content.replace(/\n/g, '') }}】
                                <template v-if="item.timeSpent > 0">耗时【{{ item.timeSpent }}h】</template>
                                结果【{{ getResultText(item.result) }}】
                            </span>
                        </div>
                    </div>
                </div>

                <!-- 安排别人的工作 -->
                <div class="work-item-section" v-if="getWorkItemsByType(2).length > 0">
                    <div class="section-header">
                        <h3 class="section-title">安排别人的工作</h3>
                    </div>
                    <div v-for="(item, index) in getWorkItemsByType(2)" :key="`assigning-${index}`" class="work-item">
                        <div class="plain-text-item">
                            <span class="plain-text-content">
                                【{{ item.itemName }}】安排【{{ item.assigner.replace(/\n/g, '') }}】完成【{{
                                    item.content.replace(/\n/g, '') }}】
                                结果【{{ getResultText(item.result) }}】
                            </span>
                        </div>
                    </div>
                </div>

                <!-- 其他工作内容 -->
                <div class="work-item-section" v-if="getWorkItemsByType(3).length > 0">
                    <div class="section-header">
                        <h3 class="section-title">其他工作内容（未在管理平台创建的任务）</h3>
                    </div>
                    <div v-for="(item, index) in getWorkItemsByType(3)" :key="`other-${index}`" class="work-item">
                        <div class="plain-text-item">
                            <span class="plain-text-content">
                                【{{ item.itemName }}】【{{ item.assigner.replace(/\n/g, '') }}】完成【{{
                                    item.content.replace(/\n/g, '') }}】
                                <template v-if="item.timeSpent > 0">耗时【{{ item.timeSpent }}h】</template>
                                结果【{{ getResultText(item.result) }}】
                            </span>
                        </div>
                    </div>
                </div></

                <!-- 市场部沟通 -->
                <div class="work-item-section" v-if="getWorkItemsByType(4).length > 0">
                    <div class="section-header">
                        <h3 class="section-title">每周与市场部沟通事宜（项目经理填写）</h3>
                    </div>
                    <div v-for="(item, index) in getWorkItemsByType(4)" :key="`market-${index}`" class="work-item">
                        <div class="plain-text-item">
                            <span class="plain-text-content">
                                【{{ item.itemName }}】与【{{ item.assigner.replace(/\n/g, '') }}】沟通【{{
                                    item.content.replace(/\n/g, '') }}】
                                结果【{{ getResultText(item.result) }}】
                            </span>
                        </div>
                    </div>
                </div>

                <!-- 标注内容 -->
                <div class="work-item-section" v-if="getWorkItemsByType(5).length > 0">
                    <div class="section-header">
                        <h3 class="section-title">标注内容：和甲方发生的无法报工作量的事宜（技术负责人，项目经理填写）</h3>
                    </div>
                    <div v-for="(item, index) in getWorkItemsByType(5)" :key="`annotation-${index}`" class="work-item">
                        <div class="plain-text-item">
                            <span class="plain-text-content">
                                【{{ item.itemName }}}}】与【{{ item.assigner.replace(/\n/g, '') }}】处理【{{
                                    item.content.replace(/\n/g, '') }}】
                                结果【{{ getResultText(item.result) }}】
                            </span>
                        </div>
                    </div>
                </div>
            </div>

            <!-- 评论区域 - 桌面端显示 -->
            <div class="comment-section" v-if="!isMobile()">
                <div class="comment-header">
                    <div class="comment-header-left">
                        <el-icon class="content-icon">
                            <ChatLineRound />
                        </el-icon>
                        <h2 class="content-title">评论</h2>
                    </div>
                    <div class="comment-header-right">
                        <!-- 评论按钮 -->
                        <el-button 
                            type="primary" 
                            size="small" 
                            @click="toggleComments"
                            class="comment-toggle-btn"
                        >
                            <el-icon>
                                <ChatLineRound />
                            </el-icon>
                            评论
                            <el-tag size="small" class="comment-count-badge">{{ comments.length }}</el-tag>
                        </el-button>
                    </div>
                </div>

                <!-- 评论列表 -->
                <div class="comment-list" v-show="showComments">
                    <template v-if="commentsLoading">
                        <div v-for="i in 3" :key="i" class="comment-item-skeleton">
                            <el-skeleton-item variant="circle" style="width: 32px; height: 32px" />
                            <div style="flex: 1; margin-left: 12px;">
                                <el-skeleton-item variant="text" style="width: 30%" />
                                <el-skeleton-item variant="text" style="width: 60%; margin-top: 8px;" />
                            </div>
                        </div>
                    </template>
                    <template v-else>
                        <CommentItem v-for="comment in comments" :key="comment.ID" :comment="comment"
                            :replying-to="replyingTo" :replying-to-author="replyingToAuthor"
                            @reply-click="handleReplyClick" />
                        <el-empty v-if="comments.length === 0" description="暂无评论" :image-size="50" />
                    </template>
                </div>

                <!-- 评论输入框 -->
                <div class="comment-input">
                    <div v-if="replyingTo" class="reply-info">
                        正在回复 @{{ replyingToAuthor }}
                        <el-button type="text" @click="cancelReply">取消</el-button>
                    </div>
                    <el-input v-model="newComment" type="textarea" :rows="2" placeholder="请输入评论内容..." resize="none"
                        maxlength="200" show-word-limit @keyup.enter="submitComment" @input="handleCommentInput" @focus="handleInputFocus" @keydown.native="handleKeyDown" @compositionstart="isComposing = true" @compositionend="onCompositionEnd" class="comment-textarea" />

                    <div v-if="showMentionList" class="mention-list-container">
                        <div class="mention-list">
                            <div class="mention-header">
                                <el-icon class="mention-icon"><User /></el-icon>
                                <span class="mention-title">选择要@的人员</span>
                                <span class="mention-count" v-if="filteredMentionUsers.length > 0">{{ filteredMentionUsers.length }}人</span>
                            </div>
                            <div class="mention-items" v-if="filteredMentionUsers.length > 0">
                                <div
                                    v-for="user in filteredMentionUsers"
                                    :key="user.id"
                                    class="mention-item"
                                    @click="selectMentionUser(user)"
                                >
                                    <div class="mention-avatar">
                                        <el-avatar :size="32" :src="user.avatar" class="user-avatar">
                                            {{ user.name.charAt(0) }}
                                        </el-avatar>
                                    </div>
                                    <div class="mention-info">
                                        <div class="mention-name">
                                            <span v-html="highlightSearchText(user.name, mentionSearchText)"></span>
                                        </div>
                                    </div>
                                    <div class="mention-action">
                                        <el-icon class="action-icon"><Plus /></el-icon>
                                    </div>
                                </div>
                            </div>
                            <div v-else class="mention-no-results">
                                <el-icon class="no-results-icon"><Search /></el-icon>
                                <span class="no-results-text">未找到匹配的人员</span>
                                <div class="no-results-tip">尝试输入姓名关键词</div>
                            </div>
                        </div>
                    </div>

                    <div class="comment-actions">
                        <el-button 
                            type="primary" 
                            size="small" 
                            @click="submitComment" 
                            :disabled="!newComment.trim() || isSubmittingComment"
                            :loading="isSubmittingComment"
                        >
                            {{ isSubmittingComment ? '提交中...' : '提交评论' }}
                        </el-button>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 移动端评论模态框 -->
    <MobileCommentModal
        v-model="showMobileCommentModal"
        :report-id="currentReport.ID || 0"
        :current-user="currentReport.author"
        @comment-submitted="handleMobileCommentSubmitted"
    />
</template>

<script lang="ts" setup>
import { ref, onMounted, onUnmounted, nextTick, watch, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { List, ChatLineRound, ArrowRight, User, Plus, Search } from '@element-plus/icons-vue'
import CommentItem from '@/views/daily/daily/CommentItem.vue'
import MobileCommentModal from '@/components/requirement/MobileCommentModal.vue'
import { GetDailyById, ToComments, GetToComments, GetDailySelectIds, GetDailyUserListByDepartment } from "@/api/newDemands/index";
import type { Comment } from '@/views/daily/daily/CommentItem.vue'
import { ElMessage } from 'element-plus'

interface WorkItem {
    workType: 1 | 2 | 3 | 4 | 5
    itemId: number
    cardId?: number
    assigner: string
    content: string
    itemName: string
    timeSpent: number
    result: 0 | 1 | 2  // 0: 未开始, 1: 完成, 2: 未完成
}

interface ItemDailyCheck {
    id: number
    checkItem: string
    isChecked: boolean
    userName?: string
    userUUID?: string
    checkDailyDate?: string
    // 可以根据实际数据结构添加更多字段
}

interface DailyReport {
    ID?: number
    cardId?: number
    status: 1 | 2
    author: string
    viewed?: boolean
    workItems: WorkItem[]
    itemDailyChecks: ItemDailyCheck[]
    summary: string
    dailyType?: number
    userName?: string
    dailyDate: string
    createAt: string
}

const route = useRoute()
const router = useRouter()
const loading = ref(true)
// 控制骨架屏：首次进入才展示，点击“下一个”不再展示骨架，仅按钮loading
const skeletonLoading = ref(true)
const workContentRef = ref<HTMLElement | null>(null)
// 过滤与顺序查看
const filterIsRead = ref<number>(2) // 1已读 2未读 3全部, 默认2
const filterNickName = ref<string>('')
const selectIds = ref<number[]>([])
const currentIndex = ref<number>(-1)
const nextDisabled = ref<boolean>(true)
const navigatingNext = ref(false)
const userOptions = ref<{ label: string; value: string }[]>([])
const reportTitle = computed(() => {
    const name = currentReport.value.author || ''
    const date = currentReport.value.dailyDate ? new Date(currentReport.value.dailyDate) : null
    if (!date || isNaN(date.getTime())) return `${name}`
    const y = date.getFullYear()
    const m = `${date.getMonth() + 1}`.padStart(2, '0')
    const d = `${date.getDate()}`.padStart(2, '0')
    return `${name}的${y}-${m}-${d}的日报`
})

const fetchSelectIds = async () => {
    try {
        const { data } = await GetDailySelectIds({ isRead: filterIsRead.value, nickName: filterNickName.value || '' })
        if (data.code === 200) {
            selectIds.value = data.data || []
            // 根据当前路由id定位索引
            const id = Number(route.params.id)
            currentIndex.value = selectIds.value.findIndex(v => v === id)
            // 若当前id不在列表中，则置为-1，从0开始
            if (currentIndex.value === -1) currentIndex.value = -1
            updateNextDisabled()
        } else {
            ElMessage.error(data.msg || '获取ID列表失败')
        }
    } catch (e) {
        ElMessage.error('获取ID列表失败')
        console.error(e)
    }
}

const updateNextDisabled = () => {
    nextDisabled.value = selectIds.value.length === 0 || currentIndex.value >= selectIds.value.length - 1
}

const goNext = () => {
    if (navigatingNext.value) return
    if (!Array.isArray(selectIds.value) || selectIds.value.length === 0) return

    navigatingNext.value = true

    const currentId = Number(route.params.id)
    const idxInList = selectIds.value.findIndex(v => v === currentId)

    if (filterIsRead.value === 2) {
        // 仅在“未读”筛选下，移除当前ID，数量立即-1
        if (idxInList !== -1) {
            selectIds.value.splice(idxInList, 1)
            currentIndex.value = idxInList // 指向移除位置的下一条
        } else {
            // 不在列表中，默认指向0
            if (currentIndex.value < 0) currentIndex.value = 0
        }
    } else {
        // 其它筛选（已读/全部）不减少数量，仅跳到下一条
        if (idxInList !== -1) {
            currentIndex.value = idxInList + 1
        } else if (currentIndex.value < 0) {
            currentIndex.value = 0
        }
    }

    updateNextDisabled()
    if (currentIndex.value >= selectIds.value.length || selectIds.value.length === 0) {
        navigatingNext.value = false
        return
    }

    const nextId = selectIds.value[currentIndex.value]
    if (nextId) {
        router.push({ name: 'DailyDetail', params: { id: nextId } })
    } else {
        navigatingNext.value = false
    }
}

const currentReport = ref<DailyReport>({
    dailyDate: '',
    createAt: '',
    status: 2,
    author: '',
    workItems: [],
    itemDailyChecks: [],
    summary: ''
})

const readers = ref<Reader[]>([])
const readersLoading = ref(false)

// 获取已读人员列表
const getReaders = async () => {
    if (!currentReport.value.itemDailyChecks) return
    
    readersLoading.value = true
    try {
        readers.value = currentReport.value.itemDailyChecks
            .filter(check => check.userName && check.userUUID && check.checkDailyDate)
            .map(check => ({
                userName: check.userName!,
                userUUID: check.userUUID!,
                checkDailyDate: check.checkDailyDate!
            }))
    } catch (error) {
        console.error('处理已读人员数据失败', error)
    } finally {
        readersLoading.value = false
    }
}

const comments = ref<Comment[]>([])
const newComment = ref('')
const replyingTo = ref<number>() // 当前正在回复的评论ID
const replyingToAuthor = ref<string>('') // 当前正在回复的用户名
const isSubmittingComment = ref(false)
const showMentionList = ref(false)
const filteredMentionUsers = ref<Staff[]>([])
const showComments = ref(false)

// 移动端评论模态框
const showMobileCommentModal = ref(false)


// 处理移动端评论提交成功
const handleMobileCommentSubmitted = () => {
    // 刷新评论数据
    getComments()
}

const toggleComments = () => {
    // 移动端使用模态框显示评论
    if (isMobile()) {
        showMobileCommentModal.value = true
        return
    }
    
    // 桌面端使用原有的展开/收起逻辑
    showComments.value = !showComments.value
    
    // 桌面端展开评论时自动滚动到评论区域
    if (showComments.value) {
        nextTick(() => {
            scrollToCommentSection()
        })
    }
}

// 获取日报详情
const loadReport = async () => {
    const id = Number(route.params.id)
    if (!id) return

    loading.value = true
    try {
        const { data } = await GetDailyById(id)
        if (data.code == 200) {
            console.log('日报详情数据:', data.data)
            currentReport.value = {
                ...data.data,
                author: data.data.userName || '',
                workItems: data.data.workItems || [],
                itemDailyChecks: data.data.itemDailyChecks || []
            }
            console.log('处理后数据:', currentReport.value)
            await Promise.all([getComments(), getReaders()])
        } else {
            ElMessage.error(data.msg)
            console.error(data.msg)
        }
    } catch (error) {
        ElMessage.error('加载日报失败')
        console.error('加载日报失败', error)
    } finally {
        loading.value = false
        // 首次加载结束后，关闭骨架屏
        if (skeletonLoading.value) skeletonLoading.value = false
    }
}

// 获取评论
const commentsLoading = ref(false)
const getComments = async () => {
    if (!currentReport.value.ID) return

    commentsLoading.value = true
    try {
        const { data } = await GetToComments(currentReport.value.ID)
        if (data.code == 200) {
            comments.value = data.data.map((item: any) => ({
                ID: item.ID,
                userName: item.userName,
                checkDailyComments: item.checkDailyComments,
                time: item.createAt, // 保持原始时间，在显示时转换
                replyTo: item.replyTo || undefined,
                replyToAuthor: item.replyToAuthor || undefined,
                replies: item.replies?.map((reply: any) => ({
                    ID: reply.ID,
                    userName: reply.userName,
                    checkDailyComments: reply.checkDailyComments,
                    time: reply.createAt, // 保持原始时间，在显示时转换
                    replyTo: reply.replyTo || undefined,
                    replyToAuthor: reply.replyToAuthor || undefined,
                    replies: reply.replies || []
                })) || []
            }))
        } else {
            ElMessage.error(data.msg)
            console.error(data.msg)
        }
    } catch (error) {
        ElMessage.error('查询评论错误')
        console.error('查询评论错误', error)
    } finally {
        commentsLoading.value = false
    }
}

// 获取所有用户
interface Staff {
    id: string
    name: string
    department: string // 部门名称
    avatar?: string // 新增头像属性
}

interface Reader {
    userName: string
    userUUID: string
    checkDailyDate: string
}
const mentionStartIndex = ref(-1)
const mentionSearchText = ref('')
// 选择提及的用户
const mentionUsers = ref<Staff[]>([])

// 初始化 @ 可选用户
const initMentionUsers = async () => {
    try {
        const { data } = await GetDailyUserListByDepartment('all')
        if (data.code === 200) {
            mentionUsers.value = (data.data || []).map((u: any) => ({
                id: u.uuid || u.userWxId || u.id || String(Math.random()),
                name: u.userName || u.nickName || u.name,
                department: '',
                avatar: u.avatar || u.headerImg || ''
            }))
        }
    } catch (e) {
        // 忽略错误，使用空列表
        console.error('获取@人员失败', e)
    }
}

// 监听文本输入变化
const handleCommentInput = () => {
    if (isComposing.value) return
    const text = newComment.value || ''

    let cursorPos = text.length
    const textarea = document.querySelector('.comment-textarea textarea') as HTMLTextAreaElement | null
    if (textarea && typeof textarea.selectionStart === 'number') {
        cursorPos = textarea.selectionStart
    }

    // 调试：输入监控
    console.log('detail.vue handleCommentInput', { text, cursorPos, lastChar: text.charAt(cursorPos - 1) })

    // 若刚输入的是 @（末位是@），直接展开
    if (cursorPos > 0 && text.charAt(cursorPos - 1) === '@') {
        console.log('detail.vue mention trigger: trailing @', { cursorPos })
        mentionStartIndex.value = cursorPos - 1
        mentionSearchText.value = ''
        showMentionList.value = true
        filteredMentionUsers.value = mentionUsers.value
        return
    }

    const lastAtPos = text.lastIndexOf('@', cursorPos - 1)
    console.log('detail.vue handleCommentInput calc', { lastAtPos })

    if (lastAtPos < 0 || cursorPos <= lastAtPos) {
        showMentionList.value = false
        mentionStartIndex.value = -1
        mentionSearchText.value = ''
        filteredMentionUsers.value = []
        return
    }

    // 更新检索词并展示
    mentionStartIndex.value = lastAtPos
    mentionSearchText.value = text.substring(lastAtPos + 1, cursorPos)

    // 如果检索词中包含空格，认为本次@结束，立即关闭列表
    if (mentionSearchText.value.includes(' ')) {
        showMentionList.value = false
        mentionStartIndex.value = -1
        mentionSearchText.value = ''
        filteredMentionUsers.value = []
        return
    }
    showMentionList.value = true

    const searchLower = mentionSearchText.value.toLowerCase()
    filteredMentionUsers.value = mentionUsers.value.filter(u => (u.name || '').toLowerCase().includes(searchLower))

    // 打开后尝试滚动到可见区域（iOS 键盘下尤为重要）
    setTimeout(() => {
        const panel = document.querySelector('.mention-list') as HTMLElement | null
        if (panel) panel.scrollIntoView({ block: 'nearest', inline: 'nearest' })
    }, 0)
}

const isComposing = ref(false)
const onCompositionEnd = () => {
    isComposing.value = false
    // 组合输入结束后再计算一次
    setTimeout(() => handleCommentInput(), 0)
}

const selectMentionUser = (user: Staff) => {
    if (mentionStartIndex.value >= 0 && user) {
        const textBefore = newComment.value.substring(0, mentionStartIndex.value)
        const textAfter = newComment.value.substring(mentionStartIndex.value + mentionSearchText.value.length + 1)
        newComment.value = `${textBefore}@${user.name} ${textAfter}`
        showMentionList.value = false
        nextTick(() => {
            const input = document.querySelector('.comment-textarea textarea') as HTMLTextAreaElement | null
            if (input) {
                input.focus()
                const cursorPos = mentionStartIndex.value + user.name.length + 2
                input.setSelectionRange(cursorPos, cursorPos)
            }
        })
    }
}

// 提交评论
const submitComment = async () => {
    if (!newComment.value.trim() || !currentReport.value.ID || isSubmittingComment.value) return

    isSubmittingComment.value = true
    try {
        const mentionedUsers = extractMentionedUsers(newComment.value)
        const { data } = await ToComments({
            dailyId: currentReport.value.ID,
            newComment: newComment.value,
            mentionedUsers: mentionedUsers,
            replyTo: replyingTo.value || undefined,
            replyToAuthor: replyingTo.value ? replyingToAuthor.value : undefined
        })

        if (data.code == 200) {
            newComment.value = ''
            cancelReply()
            getComments()
            ElMessage.success('评论提交成功')
        } else {
            ElMessage.error(data.msg)
        }
    } catch (error) {
        ElMessage.error('评论提交失败')
        console.error('评论提交失败', error)
    } finally {
        isSubmittingComment.value = false
    }
}

// 提取被@的用户
const extractMentionedUsers = (text: string) => {
    const mentions = text.match(/@([^\s]+)/g) || []
    return mentions.map(mention => mention.substring(1))
}

// 回复评论
const handleReplyClick = (comment: Comment) => {
    replyingTo.value = comment.ID
    replyingToAuthor.value = comment.userName || ''
    newComment.value = `@${replyingToAuthor.value} `
    
    // 确保评论区域展开
    if (!showComments.value) {
        showComments.value = true
    }
    
    // 移动端自动滚动到输入框
    nextTick(() => {
        scrollToCommentInput()
    })
}

// 检测是否为移动端设备
const isMobile = () => {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || 
           window.innerWidth <= 768
}

// 滚动到评论输入框
const scrollToCommentInput = () => {
    if (!isMobile()) return
    
    const commentInput = document.querySelector('.comment-input textarea') as HTMLElement
    const commentActions = document.querySelector('.comment-actions') as HTMLElement
    
    if (commentInput && commentActions) {
        // 延迟执行，确保DOM更新完成
        setTimeout(() => {
            // 获取按钮的位置
            const actionsRect = commentActions.getBoundingClientRect()
            const viewportHeight = window.innerHeight
            const keyboardHeight = viewportHeight * 0.4 // 估算键盘高度
            
            // 计算按钮底部位置
            const buttonBottom = window.pageYOffset + actionsRect.bottom
            const availableHeight = viewportHeight - keyboardHeight
            
            // 确保按钮在可见区域内，留出更多边距
            const scrollTop = buttonBottom - availableHeight + 50 // 增加边距到50px
            
            // 平滑滚动到合适位置
            window.scrollTo({
                top: Math.max(0, scrollTop),
                behavior: 'smooth'
            })
            
            // 聚焦到输入框
            setTimeout(() => {
                commentInput.focus()
                // 将光标移动到文本末尾
                const textarea = commentInput as HTMLTextAreaElement
                const textLength = textarea.value.length
                textarea.setSelectionRange(textLength, textLength)
            }, 100)
        }, 200) // 增加延迟，确保DOM完全更新
    }
}

// 滚动到评论区域（用于展开时）
const scrollToCommentSection = () => {
    if (!isMobile()) return
    
    const commentSection = document.querySelector('.comment-section') as HTMLElement
    if (commentSection) {
        // 延迟执行，确保DOM更新完成
        setTimeout(() => {
            commentSection.scrollIntoView({ 
                behavior: 'smooth', 
                block: 'start',
                inline: 'nearest'
            })
        }, 100)
    }
}

// 处理输入框焦点事件
const handleInputFocus = () => {
    if (isMobile()) {
        // 移动端输入框获得焦点时，延迟滚动以确保键盘弹出后位置正确
        setTimeout(() => {
            const commentInput = document.querySelector('.comment-input textarea') as HTMLElement
            const commentActions = document.querySelector('.comment-actions') as HTMLElement
            
            if (commentInput && commentActions) {
                // 获取按钮的位置
                const actionsRect = commentActions.getBoundingClientRect()
                const viewportHeight = window.innerHeight
                const keyboardHeight = viewportHeight * 0.4 // 估算键盘高度
                
                // 计算按钮底部位置
                const buttonBottom = window.pageYOffset + actionsRect.bottom
                const availableHeight = viewportHeight - keyboardHeight
                
                // 确保按钮在可见区域内，增加边距
                const scrollTop = buttonBottom - availableHeight + 60 // 增加边距到60px
                
                // 平滑滚动到合适位置
                window.scrollTo({
                    top: Math.max(0, scrollTop),
                    behavior: 'smooth'
                })
                
                // 确保光标在正确位置
                setTimeout(() => {
                    const textarea = commentInput as HTMLTextAreaElement
                    textarea.focus()
                    // 将光标移动到文本末尾
                    const textLength = textarea.value.length
                    textarea.setSelectionRange(textLength, textLength)
                }, 100)
            }
        }, 400) // 增加延迟，确保键盘完全弹出
    }
}

// 取消回复
const cancelReply = () => {
    replyingTo.value = undefined
    replyingToAuthor.value = ''
    
    // 移动端取消回复后恢复滚动
    if (isMobile()) {
        restoreScrollAfterCancel()
    }
}

// 移动端取消回复后恢复滚动
const restoreScrollAfterCancel = () => {
    if (!isMobile()) return
    
    // 延迟执行，确保DOM更新完成
    setTimeout(() => {
        // 保存当前滚动位置
        const currentScrollTop = window.pageYOffset
        
        // 强制重新计算页面高度和滚动
        const body = document.body
        const html = document.documentElement
        
        // 临时移除可能影响滚动的样式
        const originalOverflow = body.style.overflow
        const originalHeight = body.style.height
        
        // 重置页面高度计算
        body.style.overflow = 'auto'
        body.style.height = 'auto'
        
        // 强制重新计算
        const scrollHeight = Math.max(
            body.scrollHeight,
            body.offsetHeight,
            html.clientHeight,
            html.scrollHeight,
            html.offsetHeight
        )
        
        // 恢复原始样式
        body.style.overflow = originalOverflow
        body.style.height = originalHeight
        
        // 如果当前滚动位置为0，尝试滚动到合理位置
        if (currentScrollTop === 0 && scrollHeight > window.innerHeight) {
            // 尝试滚动到评论区域
            const commentSection = document.querySelector('.comment-section') as HTMLElement
            if (commentSection) {
                const rect = commentSection.getBoundingClientRect()
                const targetScrollTop = window.pageYOffset + rect.top - 100 // 留出一些边距
                
                window.scrollTo({
                    top: Math.max(0, targetScrollTop),
                    behavior: 'smooth'
                })
            }
        } else if (currentScrollTop > 0) {
            // 保持当前滚动位置，但确保页面可以正常滚动
            window.scrollTo({
                top: currentScrollTop,
                behavior: 'auto'
            })
        }
        
        // 触发resize事件，让浏览器重新计算视口
        setTimeout(() => {
            window.dispatchEvent(new Event('resize'))
        }, 100)
    }, 300) // 增加延迟，确保键盘完全收起
}

// 按类型获取工作项
const getWorkItemsByType = (type: number): WorkItem[] => {
    if (!currentReport.value.workItems || !Array.isArray(currentReport.value.workItems)) {
        return []
    }
    return currentReport.value.workItems.filter(item => item.workType === type)
}

// 格式化日期
// 已不展示标题，避免未使用告警
// const formatDate = (dateString: string) => {
//     if (!dateString) return ''
//     try {
//         const date = new Date(dateString);
//         if (isNaN(date.getTime())) {
//             return dateString;
//         }
//         const localDate = new Date(date.getTime() - 8 * 60 * 60 * 1000);
//         return `${localDate.getFullYear()}年${(localDate.getMonth() + 1).toString().padStart(2, '0')}月${localDate.getDate().toString().padStart(2, '0')}日`
//     } catch (error) {
//         console.error('formatDate: 日期格式化错误:', error);
//         return dateString;
//     }
// }


// 获取结果文本
const getResultText = (result: number) => {
    switch (result) {
        case 0: return '未开始'
        case 1: return '完成'
        case 2: return '未完成'
        default: return '未知状态'
    }
}

// 移动端键盘收起事件处理
const handleMobileKeyboardHide = () => {
    if (!isMobile()) return
    
    // 延迟执行，确保键盘完全收起
    setTimeout(() => {
        // 检查页面是否可以正常滚动
        const body = document.body
        const html = document.documentElement
        const scrollHeight = Math.max(
            body.scrollHeight,
            body.offsetHeight,
            html.clientHeight,
            html.scrollHeight,
            html.offsetHeight
        )
        
        // 如果页面高度大于视口高度但无法滚动，尝试修复
        if (scrollHeight > window.innerHeight && window.pageYOffset === 0) {
            // 强制重新计算页面高度
            body.style.height = 'auto'
            body.style.overflow = 'auto'
            
            // 触发resize事件
            window.dispatchEvent(new Event('resize'))
        }
    }, 500)
}

onMounted(() => {
    // 移动端添加键盘收起事件监听
    if (isMobile()) {
        // 监听视口高度变化（键盘收起时视口高度会增加）
        let lastViewportHeight = window.innerHeight
        const handleResize = () => {
            const currentHeight = window.innerHeight
            if (currentHeight > lastViewportHeight) {
                // 视口高度增加，可能是键盘收起了
                handleMobileKeyboardHide()
            }
            lastViewportHeight = currentHeight
        }
        
        window.addEventListener('resize', handleResize)
        
        // 在组件卸载时移除监听器
        onUnmounted(() => {
            window.removeEventListener('resize', handleResize)
        })
    }
    fetchSelectIds()
    // 初始化用户下拉：参考项目接口，根据部门获取用户列表（传空表示所有）
    initUserOptions()
    loadReport()

    // 防止 iOS 弹性回弹：拦截滚动到边界继续滚动导致的反弹
    const el = workContentRef.value
    if (el) {
        const handleWheel = (e: WheelEvent) => {
            const target = el
            const delta = e.deltaY
            const atTop = target.scrollTop <= 0
            const atBottom = Math.ceil(target.scrollTop + target.clientHeight) >= target.scrollHeight
            if ((atTop && delta < 0) || (atBottom && delta > 0)) {
                e.preventDefault()
            }
        }
        el.addEventListener('wheel', handleWheel, { passive: false })
    }

    // 全局阻止外层滚动与回弹：仅允许工作内容容器滚动
    const stopBodyScroll = (e: TouchEvent) => {
        const target = e.target as HTMLElement | null
        const container = workContentRef.value
        if (!container || !target) return

        // 允许工作内容区域滚动
        let allowed = container.contains(target)

        // 允许 Element Plus 下拉选择面板内滚动
        if (!allowed) {
            const dropdown = target.closest('.el-select__popper, .el-select-dropdown, .el-scrollbar__wrap')
            if (dropdown) allowed = true
        }

        if (!allowed) {
            e.preventDefault()
        }
    }
    document.addEventListener('touchmove', stopBodyScroll, { passive: false })
    // 修正 body/html 底部空白：路由进入时锁定高度与滚动
    document.body.classList.add('no-extra-space')
    document.documentElement.classList.add('no-extra-space')
    const appRoot = document.getElementById('app')
    if (appRoot) appRoot.classList.add('no-extra-space')

    onUnmounted(() => {
        const el2 = workContentRef.value
        if (el2) {
            el2.removeEventListener('wheel', (() => {}) as any)
        }
        document.removeEventListener('touchmove', stopBodyScroll as any)
        document.body.classList.remove('no-extra-space')
        document.documentElement.classList.remove('no-extra-space')
        const appRoot2 = document.getElementById('app')
        if (appRoot2) appRoot2.classList.remove('no-extra-space')
    })
    // 初始化 @ 用户
    initMentionUsers()
})

// 监听路由变化以重载详情与校准当前位置
watch(() => route.params.id, async () => {
    // 加载当前日报
    await loadReport()
    // 不再强制刷新ID列表，保持“数量-1”的乐观更新
    // 路由变化后尝试重新对齐索引与按钮状态
    const id = Number(route.params.id)
    if (selectIds.value.length > 0) {
        currentIndex.value = selectIds.value.findIndex(v => v === id)
    } else {
        currentIndex.value = -1
    }
    updateNextDisabled()
    // 完成加载，结束导航loading
    navigatingNext.value = false
})

// 监听筛选条件变化自动查询
watch(filterIsRead, () => {
    fetchSelectIds()
})

let nickNameDebounceTimer: any
watch(filterNickName, () => {
    if (nickNameDebounceTimer) clearTimeout(nickNameDebounceTimer)
    nickNameDebounceTimer = setTimeout(() => {
        fetchSelectIds()
    }, 400)
})

// 用户下拉：初始化与变更
const initUserOptions = async () => {
    try {
        const { data } = await GetDailyUserListByDepartment('')
        if (data.code === 200) {
            userOptions.value = (data.data || []).map((u: any) => ({
                label: u.userName || u.nickName || u.name,
                value: u.userName || u.nickName || u.name
            }))
        }
    } catch (e) {
        console.error('获取用户下拉失败', e)
    }
}

const onUserChange = () => {
    // 直接触发查询
    fetchSelectIds()
}

const onUserClear = () => {
    filterNickName.value = ''
    fetchSelectIds()
}

// 处理输入框键入事件
const handleKeyDown = (e: KeyboardEvent) => {
    // 统一在下一帧用 v-model 值判断（iOS 输入法延迟，上调为 30ms）
    setTimeout(() => {
        const text = newComment.value || ''
        const textarea = document.querySelector('.comment-textarea textarea') as HTMLTextAreaElement | null
        const cursorPos = textarea?.selectionStart ?? text.length
        console.log('detail.vue handleKeyDown', { key: e.key, text, cursorPos, lastChar: text.charAt(cursorPos - 1) })

        // 空格键：若正在显示@列表，则立即关闭
        if ((e.key === ' ' || text.charAt(cursorPos - 1) === ' ') && showMentionList.value) {
            showMentionList.value = false
            mentionStartIndex.value = -1
            mentionSearchText.value = ''
            filteredMentionUsers.value = []
            return
        }
        // 如果末尾刚输入 @，直接打开
        if (cursorPos > 0 && text.charAt(cursorPos - 1) === '@') {
            console.log('detail.vue mention trigger: keydown trailing @', { cursorPos })
            mentionStartIndex.value = cursorPos - 1
            mentionSearchText.value = ''
            showMentionList.value = true
            filteredMentionUsers.value = mentionUsers.value
            return
        }

        if (showMentionList.value) {
            const lastAtPos = text.lastIndexOf('@', cursorPos - 1)
            console.log('detail.vue handleKeyDown calc', { lastAtPos })
            if (lastAtPos >= 0) {
                mentionStartIndex.value = lastAtPos
                mentionSearchText.value = text.substring(lastAtPos + 1, cursorPos)
                showMentionList.value = true
                const searchLower = mentionSearchText.value.toLowerCase()
                filteredMentionUsers.value = mentionUsers.value.filter(u => (u.name || '').toLowerCase().includes(searchLower))
            } else {
                showMentionList.value = false
            }
        }

        if (e.key === 'Backspace' || e.key === 'Delete') {
            const lastAtPos = text.lastIndexOf('@', cursorPos - 1)
            const searchText = lastAtPos >= 0 ? text.substring(lastAtPos + 1, cursorPos).trim() : ''
            console.log('detail.vue delete check', { lastAtPos, searchText })
            if (lastAtPos < 0 || cursorPos <= lastAtPos || searchText === '') {
                showMentionList.value = false
                mentionStartIndex.value = -1
                mentionSearchText.value = ''
                filteredMentionUsers.value = []
            }
        }
    }, 30)
}

// 高亮搜索文本
const highlightSearchText = (text: string, searchText: string) => {
    if (!searchText) return text
    const regex = new RegExp(`(${searchText})`, 'gi')
    return text.replace(regex, '<span class="highlight">$1</span>')
}
</script>

<style scoped>
#app.no-extra-space, html.no-extra-space, body.no-extra-space {
    height: 100dvh;
    overflow: hidden;
}
/* 基础变量 */
:root {
    --primary-color: #409EFF;
    --success-color: #67C23A;
    --warning-color: #E6A23C;
    --danger-color: #F56C6C;
    --info-color: #909399;
    --text-primary: #303133;
    --text-regular: #606266;
    --text-secondary: #909399;
    --border-color: #DCDFE6;
    --bg-color: #F5F7FA;
}

/* 基础布局 */
.daily-detail-container {
    height: calc(100dvh - 90px);
    font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", sans-serif;
    background: #fff;
    padding: 20px 20px 8px 20px;
    border-radius: 8px;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    overscroll-behavior: none;
    -webkit-overflow-scrolling: auto;
    margin-bottom: 0;
}

/* 头部区域 */
.report-header {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 16px;
}

.report-title {
    font-size: 16px;
    font-weight: 700;
    color: #1f2937;
    margin: 0;
    text-align: center;
}

.header-right {
    display: flex;
    gap: 10px;
}

/* 元信息区域 */
.report-meta-info {
    margin-bottom: 24px;
}

.meta-text {
    font-size: 16px;
    color: var(--text-regular);
}

/* 工作内容区域 */
.work-content-container {
    flex: 1;
    display: flex;
    flex-direction: column;
    overflow: hidden;
    min-height: 0; /* 允许子元素flex滚动区域占满 */
}

/* 允许 Element Plus 下拉面板在移动端独立滚动 */
:deep(.el-select__popper), :deep(.el-select-dropdown), :deep(.el-scrollbar__wrap) {
    touch-action: pan-y;
    overscroll-behavior: contain;
}

/* 下拉面板限制高度（teleported=false 时在本组件内） */
:deep(.user-select-popper .el-scrollbar__wrap),
:deep(.user-select-popper .el-select-dropdown__wrap) {
    max-height: 170px !important; /* 5 * 34px */
    overflow: auto !important;
}

.work-content-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
}

.work-content-header-left {
    display: flex;
    align-items: center;
}

.work-content-header-right {
    display: flex;
    align-items: center;
    gap: 8px;
}

.mobile-comment-btn {
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.2s ease;
    font-size: 12px;
    padding: 6px 12px;
    display: flex;
    align-items: center;
    gap: 4px;
}

/* 顶部筛选布局优化 */
.filters-group {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: nowrap;
    overflow-x: visible;
    white-space: nowrap;
}
.filters-group .filter-select {
    flex: 0 0 18%;
    min-width: 80px;
}
.filters-group .filter-input {
    flex: 0 0 28%;
    min-width: 110px;
}
.filters-group .filters-divider {
    margin: 0 6px;
}
.filters-group .next-button {
    flex: 0 0 auto;
    border: none;
    background: linear-gradient(135deg, #22c55e 0%, #16a34a 100%);
    color: #fff;
    font-weight: 600;
    border-radius: 8px;
    padding: 0 14px;
}

.ids-count-badge {
    background: #eef2ff;
    color: #4f46e5;
    border: 1px solid #e0e7ff;
}

.filter-select-badge {
    display: inline-flex;
    align-items: center;
    gap: 6px;
}
.ids-count-badge-mini {
    background: #eef2ff;
    color: #4f46e5;
    border: 1px solid #e0e7ff;
}

.isread-count-badge :deep(.el-badge__content) {
    transform: translate(4px, -6px);
}

/* 新增：筛选区域容器 */
.work-content-filters {
    margin-bottom: 12px;
    background: #ffffff;
    border: 1px solid #e8eef7;
    border-radius: 10px;
    padding: 14px 16px;
    min-height: 64px;
    width: 100%;
    box-sizing: border-box;
}

.mobile-comment-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.content-icon {
    color: #3b82f6;
    margin-right: 8px;
}

.content-title {
    font-size: 18px;
    font-weight: 700;
    margin: 0;
    color: #334155;
}

.work-items-container {
    flex: 1 1 0%;
    overflow-y: auto;
    overflow-x: hidden;
    -webkit-overflow-scrolling: auto;
    overscroll-behavior: contain;
    touch-action: pan-y;
    padding-right: 8px;
    margin-bottom: 0;
    padding-bottom: 4px; /* 防止最后一行被裁切 */
    min-height: 0; /* 防止出现未使用的底部空白 */
}

/* 工作项样式 */
.work-item-section {
    margin-bottom: 24px;
}

.section-header {
    margin-bottom: 12px;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.section-title {
    font-size: 16px;
    font-weight: 500;
    color: var(--text-primary);
    margin: 0;
}

.work-item {
    margin-bottom: 12px;
    padding: 12px;
    background-color: var(--bg-color);
    border-radius: 6px;
    transition: all 0.3s ease;
}

.work-item:hover {
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.plain-text-content {
    font-size: 14px;
    line-height: 1.6;
    color: var(--text-primary);
    word-break: break-word;
}

/* 评论区域 */
.comment-section {
    border-top: 1px solid var(--border-color);
    padding-top: 12px;
    margin-top: 4px;
    flex-shrink: 0;
    padding-bottom: 8px; /* 给底部留缓冲，避免挤白 */
}

/* 中央转圈加载样式 */
.next-loading-overlay {
    position: fixed;
    inset: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    background: rgba(255, 255, 255, 0.6);
    z-index: 9999;
}
.next-loading-content {
    display: flex;
    flex-direction: column;
    align-items: center;
    gap: 10px;
    padding: 18px 20px;
    background: #ffffff;
    border: 1px solid #e5e7eb;
    border-radius: 14px;
    box-shadow: 0 12px 36px rgba(0,0,0,0.12);
}
.ring-spinner {
    width: 40px;
    height: 40px;
    border: 3px solid rgba(59,130,246,0.2);
    border-top-color: #3b82f6;
    border-radius: 50%;
    animation: spin 0.9s linear infinite;
}
.next-loading-text {
    font-size: 14px;
    color: #374151;
}
.next-loading-subtext {
    font-size: 12px;
    color: #6b7280;
}
@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.comment-header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-bottom: 16px;
    padding: 8px 0;
}

.comment-header-left {
    display: flex;
    align-items: center;
    gap: 8px;
}

.comment-header-right {
    display: flex;
    align-items: center;
    gap: 8px;
}

.comment-count-tag { 
    margin: 0;
}

.readers-count-tag {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    border: none;
    font-weight: 500;
    font-size: 12px;
}

.comment-toggle-btn {
    border-radius: 6px;
    font-weight: 500;
    transition: all 0.2s ease;
}

.comment-toggle-btn:hover {
    transform: translateY(-1px);
    box-shadow: 0 2px 8px rgba(59, 130, 246, 0.3);
}

.comment-count-badge {
    margin-left: 6px;
    background: rgba(255, 255, 255, 0.2);
    color: white;
    border: 1px solid rgba(255, 255, 255, 0.3);
    font-weight: 600;
    font-size: 11px;
    min-width: 18px;
    height: 18px;
    line-height: 16px;
    padding: 0 4px;
    border-radius: 9px;
}

.comment-list {
    max-height: 300px;
    overflow-y: auto;
    margin-bottom: 16px;
    padding-right: 12px;
    /* 确保滚动条可见 */
    scrollbar-width: thin;
    scrollbar-color: #cbd5e1 #f1f5f9;
}

/* 自定义滚动条样式 */
.comment-list::-webkit-scrollbar {
    width: 6px;
}

.comment-list::-webkit-scrollbar-track {
    background: #f1f5f9;
    border-radius: 3px;
}

.comment-list::-webkit-scrollbar-thumb {
    background: #cbd5e1;
    border-radius: 3px;
}

.comment-list::-webkit-scrollbar-thumb:hover {
    background: #94a3b8;
}

/* 评论输入区域 */
.comment-input {
    margin-top: 16px;
}

.comment-actions {
    margin-top: 12px;
    text-align: right;
}

.comment-actions .el-button {
    transition: all 0.3s ease;
    position: relative;
    overflow: hidden;
}

.comment-actions .el-button:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}

.comment-actions .el-button.is-loading {
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    border-color: #3b82f6;
    color: white;
}

.reply-info {
    margin-bottom: 12px;
    padding: 8px 12px;
    background-color: var(--bg-color);
    border-radius: 4px;
    color: var(--text-regular);
    font-size: 14px;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

/* 提及列表 */
.mention-list-container {
    position: relative;
    margin-top: 8px;
}

.mention-list {
    position: absolute;
    top: 100%;
    left: 0;
    margin-top: 10px;
    width: 100%;
    max-height: 220px;
    overflow-y: auto;
    background: #fff;
    border: 1px solid var(--border-color);
    border-radius: 8px;
    box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
    z-index: 2000; /* 提升层级，避免在 iOS 下被遮挡 */
}

.mention-header {
    display: flex;
    align-items: center;
    gap: 8px;
    padding: 8px 12px;
    background-color: var(--bg-color);
    border-bottom: 1px solid var(--border-color);
}

.mention-icon {
    color: var(--primary-color);
}

.mention-title {
    font-size: 14px;
    color: var(--text-regular);
    font-weight: 500;
}

.mention-count {
    font-size: 12px;
    color: var(--text-secondary);
    background: #eef2ff;
    border: 1px solid #e0e7ff;
    border-radius: 6px;
    padding: 2px 6px;
    font-weight: 600;
}

.mention-items {
    max-height: 150px; /* 控制下拉列表的最大高度 */
    overflow-y: auto;
}

.mention-item {
    display: flex;
    align-items: center;
    padding: 8px 12px;
    cursor: pointer;
    transition: all 0.2s;
}

.mention-item:hover {
    background-color: var(--bg-color);
    color: var(--primary-color);
}

.mention-avatar {
    flex-shrink: 0;
    margin-right: 10px;
}

.user-avatar {
    background-color: var(--primary-color);
    color: white;
}

.mention-info {
    flex: 1;
    min-width: 0; /* 允许子项收缩 */
}

.mention-name {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}

.mention-action {
    flex-shrink: 0;
    margin-left: 10px;
    opacity: 0; /* 默认隐藏 */
    transition: opacity 0.2s ease;
}

.mention-item:hover .mention-action {
    opacity: 1; /* 鼠标悬停时显示 */
}

.action-icon {
    color: var(--primary-color);
    font-size: 16px;
}

.mention-no-results {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20px 0;
    color: var(--text-secondary);
    font-size: 14px;
}

.no-results-icon {
    font-size: 36px;
    margin-bottom: 8px;
}

.no-results-text {
    font-weight: 500;
}

.no-results-tip {
    font-size: 12px;
    color: var(--text-secondary);
    margin-top: 4px;
}

/* 骨架屏样式 */
.comment-item-skeleton {
    display: flex;
    padding: 12px;
    margin-bottom: 12px;
    background-color: #fff;
    border-radius: 4px;
    align-items: center;
}

/* 已读人员样式 */
.readers-container {
    margin-bottom: 16px;
    background: linear-gradient(180deg, #f8fbff 0%, #ffffff 100%);
    border: 1px solid #e8eef7;
    border-radius: 10px;
    padding: 12px 14px;
}

.readers-header {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    justify-content: space-between;
}
.readers-left { display: inline-flex; align-items: center; gap: 8px; min-width: 0; }

.readers-title {
    display: flex;
    align-items: center;
    gap: 8px;
    min-width: 0; /* 允许子项收缩 */
}
.readers-label {
    font-size: 14px;
    font-weight: 700;
    color: #1f2937;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.readers-count {
    background: #eef2ff;
    color: #4f46e5;
    border: 1px solid #e0e7ff;
}

@media (max-width: 480px) {
    .readers-label {
        font-size: 13px;
    }
}

.readers-list {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.reader-tag {
    margin-right: 0;
    margin-bottom: 0;
    background-color: #eef5ff;
    border-color: #cfe2ff;
    color: #2563eb;
}

/* 响应式处理 */
@media (max-width: 768px) {
    .daily-detail-container {
        padding: 16px;
    }

    .report-header {
        flex-direction: column;
        align-items: flex-start;
        gap: 12px;
    }

    .work-item {
        padding: 8px;
    }
    
    /* 移动端工作内容区域优化 */
    .work-content-container {
        height: calc(100% - 40px);
        padding: 12px;
    }
    
    .work-items-container {
        max-height: 75%;
        min-height: 300px;
        /* 移动端工作项网格优化 */
        display: block;
    }
    
    /* 移动端工作项样式优化 */
    .work-item-grid {
        grid-template-columns: 1fr;
        gap: 8px;
    }
    
    .work-item {
        margin-bottom: 8px;
        padding: 12px;
        /* 移动端工作项内容优化 */
        font-size: 14px;
        line-height: 1.5;
    }
    
    /* 移动端工作内容标题优化 */
    .content-title {
        font-size: 18px;
        margin-bottom: 12px;
    }
    
    /* 移动端工作内容头部优化 */
    .work-content-header {
        margin-bottom: 12px;
        padding-bottom: 8px;
        align-items: center;
    }

    .filters-group {
        width: 100%;
        gap: 6px;
        flex-wrap: nowrap;
        overflow-x: visible;
        white-space: nowrap;
    }
    .filters-group .filter-select {
        flex: 0 0 28%;
        min-width: 80px;
    }
    .filters-group .filter-input {
        flex: 0 0 40%;
        min-width: 100px;
    }
    .filters-group .filters-divider {
        display: none;
    }
    
    /* 移动端评论输入框优化 */
    .comment-input {
        position: relative;
        z-index: 10;
    }
    
    .comment-input :deep(.el-textarea__inner) {
        font-size: 16px; /* 防止iOS缩放 */
        border-radius: 12px;
        padding: 12px;
        line-height: 1.5;
        /* 确保光标正确显示 */
        caret-color: #3b82f6;
        /* 防止输入框被键盘遮挡 */
        position: relative;
        z-index: 1000;
    }
    
    .comment-section {
        margin-bottom: 20px;
        /* 确保评论区域在移动端有足够的空间 */
        min-height: 200px;
    }
    
    /* 确保输入框在移动端有足够的可见空间 */
    .comment-input :deep(.el-textarea) {
        margin-bottom: 10px;
    }
    
    /* 移动端评论输入区域优化 */
    .comment-input {
        padding-bottom: 20px;
    }
    
    .comment-input :deep(.el-textarea__inner) {
        min-height: 80px;
    }
    
    /* 移动端评论区域展开时的额外样式 */
    .comment-section.expanded {
        padding-bottom: 20px;
    }
    
    /* 移动端增加底部间距，确保提交按钮不被遮挡 */
    .comment-section {
        padding-bottom: 80px;
    }
    
    /* 确保评论区域在移动端不会被遮挡 */
    .comment-section {
        scroll-margin-top: 20px;
    }
    
    /* 移动端评论列表滚动条优化 */
    .comment-list {
        padding-right: 16px; /* 增加右侧内边距 */
        /* 移动端滚动条样式 */
        scrollbar-width: thin;
        scrollbar-color: #3b82f6 #f1f5f9;
    }
    
    .comment-list::-webkit-scrollbar {
        width: 8px; /* 移动端稍微宽一点 */
    }
    
    .comment-list::-webkit-scrollbar-track {
        background: #f1f5f9;
        border-radius: 4px;
    }
    
    .comment-list::-webkit-scrollbar-thumb {
        background: #3b82f6;
        border-radius: 4px;
    }
    
    .comment-list::-webkit-scrollbar-thumb:hover {
        background: #1d4ed8;
    }
    
    /* 移动端评论操作区域优化 */
    .comment-actions {
        position: sticky;
        bottom: 0;
        background: #ffffff;
        padding: 12px 0;
        margin-top: 12px;
        border-top: 1px solid #e5e7eb;
        z-index: 100;
    }
    
    .comment-actions .el-button {
        width: 100%;
        height: 44px;
        font-size: 16px;
        font-weight: 600;
        border-radius: 12px;
        transition: all 0.3s ease;
    }
    
    .comment-actions .el-button:disabled {
        opacity: 0.6;
        cursor: not-allowed;
    }
    
    .comment-actions .el-button.is-loading {
        background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
        border-color: #3b82f6;
    }
}

/* 超小屏幕设备优化 */
@media (max-width: 480px) {
    .work-content-container {
        height: calc(100% - 30px);
        padding: 8px;
    }
    
    .work-items-container {
        max-height: 80%;
        min-height: 250px;
    }
    
    .work-item {
        padding: 10px;
        font-size: 13px;
    }
    
    .content-title {
        font-size: 16px;
    }
}
</style>

<style>
/* 全局样式：解决移动端底部空白与外层滚动问题 */
html.no-extra-space, body.no-extra-space, #app.no-extra-space {
    height: 100dvh !important;
    overflow: hidden !important;
}
</style>